package com.movie.recomend.controller;

import com.movie.recomend.model.domain.User;
import com.movie.recomend.model.request.LoginUserRequest;
import com.movie.recomend.model.request.RegisterUserRequest;
import com.movie.recomend.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.Arrays;

@CrossOrigin
@RequestMapping("/rest/users")
@RestController
public class UserRestApi {

    @Autowired
    private UserService userService;


    @RequestMapping(value = "/login", method = RequestMethod.GET)
    public User login(@RequestParam("username") String username, @RequestParam("password") String password) {
        User user = userService.loginUser(new LoginUserRequest(username, password));
        System.out.println("user = " + user);
        return user;
    }

    @RequestMapping(value = "/register", method = RequestMethod.GET)
    public User addUser(@RequestParam("username") String username, @RequestParam("password") String password) {
        if (userService.checkUserExist(username)) {
            return null;
        }
        if (userService.registerUser(new RegisterUserRequest(username, password))) {
            return userService.findByUsername(username);
        }
        return null;
    }

    //冷启动问题
    @RequestMapping(value = "/pref", produces = "application/json", method = RequestMethod.GET)
    @ResponseBody
    public Boolean addPrefGenres(@RequestParam("username") String username, @RequestParam("genres") String genres) {
        User user = userService.findByUsername(username);
        user.getPrefGenres().addAll(Arrays.asList(genres.split(",")));
        user.setFirst(false);
        return userService.updateUser(user);
    }

    @RequestMapping(value = "/get", method = RequestMethod.GET)
    public User getUser(@RequestParam("username") String username) {
        User user = userService.findByUsername(username);
        return user;
    }
}
